<template>
  <el-dialog
    title="批量添加素材"
    v-model="dialogVisible"
    width="98vw"
    top="5vh"
  >
    <webview
      ref="webviewRef"
      style="height: 500px; margin-bottom: 10px"
      src="https://bdw.bingdou.site/shipin/index.html#/classification/2?_useType=selectVideo"
    ></webview>
    <span slot="footer">
      <el-button @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onOk">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { nextTick, computed, ref, onMounted } from "vue";
export default {
  props: ["visible", "propData", "fragment"],
  emit: ["changeVisible", "updateVideos"],
  setup(props, context) {
    const dialogVisible = computed({
      get() {
        return props.visible;
      },
      set(value) {
        context.emit("changeVisible", value);
      },
    });
    const webviewRef = ref();
    onMounted(() => {
      nextTick(() => {
        // 测试的时候使用的代码
        webviewRef.value.addEventListener("dom-ready", () => {
          // webviewRef.value.openDevTools();
          onResetStorage();
        });
      });
    });
    const onCancel = () => {
      dialogVisible.value = false;
    };

    const isVideoLink = (item, old_list) => {
      const url = item.url;
      const id = item.id;
      var videoExtensions = [
        ".mp4",
        ".mov",
        ".avi",
        ".mkv",
        ".wmv",
        ".flv",
        ".rmvb",
        ".3gp",
        ".webm",
        ".mpeg",
      ];
      var fileExtension = url.substring(url.lastIndexOf(".")).toLowerCase();
      return (
        videoExtensions.includes(fileExtension) &&
        old_list.findIndex((item) => item.id === id) === -1
      );
    };
    const onResetStorage = async () => {
      await webviewRef.value.executeJavaScript(
        `localStorage.removeItem('videoSelectStore');`
      );
    };
    const onOk = async () => {
      const data = await webviewRef.value.executeJavaScript(
        `localStorage.getItem('videoSelectStore');`
      );
      const videoArray = JSON.parse(data);
      const old_list = props.propData ? props.propData.dataList : [];
      const selectVideo = videoArray.filter((item) =>
        isVideoLink(item, old_list)
      );
      let list = [...selectVideo].map((item) => {
        item.type = 1;
        return item;
      });
      context.emit("updateVideos", [...old_list, ...list], props.fragment);
    };

    return {
      webviewRef,
      dialogVisible,
      onCancel,
      onOk,
    };
  },
};
</script>
<style scoped></style>
